package switchviz.core.alias;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.TreeSelectionModel;

import org.apache.log4j.Logger;

import switchviz.core.ResourceManager;
import switchviz.core.mib.MIBTree;
import switchviz.gui.component.IListener;
import switchviz.gui.component.PopupMenu;
import switchviz.gui.component.XMLTreeNode;

public class AliasPanel extends JPanel implements IListener, ComponentListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(AliasPanel.class);
	private AliasConfigurationPanel _aliaspanel = null;
	private MIBTree _mibtree; 
	private AliasTree _aliastree;
	private AliasDataModel _aliasmodel;
	private PopupMenu _aliaspopup = null;
	private PopupMenu _mibpopup = null;
	
	public AliasPanel()
	{
		if (logger.isInfoEnabled()) { logger.info("Initialize ..."); }
		initialize();
	}
	
	private void initialize()
	{
    	JPanel mibPanel = new JPanel(new BorderLayout(3, 3));
    	JPanel aliasConfPanel = new JPanel(new BorderLayout(3, 3));

		JButton ButtTransfer = new JButton("Transfer Selection", ResourceManager.getInstance().getImageIconTransfer());
		ButtTransfer.addActionListener(this);
		ButtTransfer.setActionCommand(ResourceManager.getInstance().getActionTransfer());
		
		mibPanel.add(getMIBTree(), BorderLayout.CENTER);
		mibPanel.add(ButtTransfer, BorderLayout.SOUTH);

		aliasConfPanel.add(getAliasPanel(), BorderLayout.SOUTH);
		aliasConfPanel.add(getAliasTree(), BorderLayout.CENTER);
		
		this.setLayout(ResourceManager.getInstance().getBorderLayout());
		this.add(mibPanel, BorderLayout.WEST);
		this.add(aliasConfPanel, BorderLayout.CENTER);
		this.addComponentListener(this);
	}
	
	private MIBTree getMIBTree()
	{
		if (_mibtree == null)
		{
			try 
			{
				_mibtree = new MIBTree(ResourceManager.getInstance().getMIBConfigurationFile());
				_mibtree.getTree().getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
				_mibtree.getTree().addMouseListener(this);
				_mibpopup = new PopupMenu(new String[] { ResourceManager.getInstance().getActionTransfer(), 
					ResourceManager.getInstance().getActionRefresh() }, this);
			} 
			catch (Exception e) { logger.error(e.getMessage()); }
		}
		return _mibtree;
	}
	
	private AliasTree getAliasTree()
	{
		if (_aliastree == null)
		{
			try 
			{
				_aliastree = new AliasTree(ResourceManager.getInstance().getAliasConfigurationFile());
				_aliastree.getTree().getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
				_aliastree.getTree().addTreeSelectionListener(this);
				_aliastree.getTree().addMouseListener(this);
				_aliaspopup = new PopupMenu(new String[] {
					ResourceManager.getInstance().getActionRemoveItem(), 
					ResourceManager.getInstance().getActionRefresh() }, this);
			} 
			catch (Exception e) { logger.error(e.getMessage()); }
		}
		return _aliastree;
	}
	
	private AliasDataModel getAliasModel()
	{
		if (_aliasmodel == null)
		{
			_aliasmodel = new AliasDataModel();
		}
		return _aliasmodel;
	}
	
	private AliasConfigurationPanel getAliasPanel()
	{
		if (_aliaspanel == null)
		{
			_aliaspanel = new AliasConfigurationPanel();
			_aliaspanel.addListener(this);
		}
		return _aliaspanel;
	}

	public void actionPerformed(ActionEvent evt) 
	{
		String command = evt.getActionCommand();
		try 
    	{
	        if (ResourceManager.getInstance().getActionRemoveItem().equals(command))
	        {
	        	if (getAliasTree().getTree().getSelectionCount() > 0)
	        	{
	        		getAliasTree().deleteSelection(getAliasTree().getTree().getSelectionPaths());
	        		getAliasTree().saveXML();
	        	}
	        }
	        else if(ResourceManager.getInstance().getActionRefresh().equals(command))
	        {
	        	reload();
	        }
	        else if (ResourceManager.getInstance().getActionTransfer().equals(command))
	        {
	        	if (getMIBTree().getTree().getSelectionCount() > 0)
	        	{
	        		getAliasTree().transferSelection(getMIBTree().getTree().getSelectionPaths());
	        		getAliasTree().saveXML();
		        	getAliasTree().reload();
		        	getAliasTree().getTree().setSelectionRow(0);
	        	}
	        }
	        else if (ResourceManager.getInstance().getActionApply().equals(command))
	        {
	        	if (((XMLTreeNode)getAliasTree().getTree().getLastSelectedPathComponent()).isRoot()) { return; }
	    		_aliasmodel = getAliasPanel().getValues();
	        	if (_aliasmodel.getAlias().trim().equals("") || _aliasmodel.getOIDPath().trim().equals(""))
	    		{
	    			JOptionPane.showMessageDialog(this,
	    				    "Please insert an alias and an id path.",
	    				    "Form not complete!",
	    				    JOptionPane.WARNING_MESSAGE);
	    			return;
	    		}
	    		getAliasTree().changeCurrentNode(_aliasmodel);
	    		getAliasTree().saveXML();
	        }
    	}
		catch (Exception e1) { logger.error(e1.getMessage()); }
	}
	

	public void valueChanged(TreeSelectionEvent evt) 
	{
		XMLTreeNode currentnode = (XMLTreeNode)evt.getPath().getLastPathComponent();
		if (currentnode.isRoot()) 
		{ 
			getAliasModel().setAlias("");
			getAliasModel().setNamePath("");
			getAliasModel().setOIDPath("");
			getAliasModel().setDescription("");
		}
		else
		{
			getAliasModel().setAlias(currentnode.getElement().getName());
			getAliasModel().setNamePath(currentnode.getElement().getAttributeValue(AliasTree.ALIASNODENAMEPATH));
			getAliasModel().setOIDPath(currentnode.getElement().getAttributeValue(AliasTree.ALIASNODEOIDPATH));
			getAliasModel().setDescription(currentnode.getElement().getTextNormalize());
		}
		getAliasPanel().setValues(getAliasModel());
	}
	
	public void mousePressed(MouseEvent e) 
	{
		if (e.isPopupTrigger() || e.getButton() == 3) 
		{
			if(e.getSource().equals(_aliastree.getTree()))
				_aliaspopup.show(e.getComponent(), e.getX(), e.getY());
			else
				_mibpopup.show(e.getComponent(), e.getX(), e.getY());
        }
	}
	
	private void reload()
	{
		try 
		{
	    	getMIBTree().reload();
	    	getMIBTree().getTree().setSelectionRow(0);
	    	getAliasTree().reload();
	    	getAliasTree().getTree().setSelectionRow(0);
		} 
		catch (Exception e) 
		{
			logger.error(e.getMessage()); 
			e.printStackTrace();
		}
	}
	
	public void componentShown(ComponentEvent evt) 
	{
		reload();
	}
	
	public void componentHidden(ComponentEvent arg0) {}
	public void componentMoved(ComponentEvent arg0) {}
	public void componentResized(ComponentEvent arg0) {}
	
	public void mouseClicked(MouseEvent arg0) {}
	public void mouseEntered(MouseEvent arg0) {}
	public void mouseExited(MouseEvent arg0) {}
	public void mouseReleased(MouseEvent arg0) {}
}

